package com.longlonggo.config;

import java.io.IOException;
import java.util.List;
import java.util.Properties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerProperties;
import org.springframework.context.annotation.Bean;
import freemarker.template.Configuration;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import com.google.common.collect.Lists;
import freemarker.template.TemplateException;

/**
 * fremarker自定义配置，用于配置宏定义标签
 * 
 * @author 石马人山 me@longlonggo.com
 * @Created 2018年5月2日 下午8:32:30
 *          </p>
 * @version 100-000-000<br/>
 * @description <br/>
 */
@org.springframework.context.annotation.Configuration
public class FreeMarkerConfig {

	/**
	 * 拿到spring boot中的freemarker的自动化配置
	 */
	@Autowired
	private FreeMarkerProperties properties;

	/**
	 * 覆盖spring boot中的freemarker配置
	 *
	 * @return
	 */
	@Bean
	public FreeMarkerConfigurer freeMarkerConfigurer() {
		// 写入配置
		FreeMarkerConfigurer factory = new FreeMarkerConfigurer();
		writerProperties(factory);

		// 创建fm的配置，并且将factory中的信息写入到configuration中
		Configuration configuration = null;
		try {
			configuration = factory.createConfiguration();
			// 和spring boot不同的部分，这部分是用来写入我们需要的freemarker configuration
			List<String> autoIncludes = Lists.newArrayListWithCapacity(1);
			// 注意macro\macro.ftl这个路径是和在spring.freemarker.template-loader-path下
			autoIncludes.add("include\\framework.ftl");
			configuration.setAutoIncludes(autoIncludes);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		factory.setConfiguration(configuration);
		return factory;
	}

	/**
	 * 将配置文件重新写入到freemarker配置类中，执行自定义配置
	 * 
	 * @param factory
	 */
	private void writerProperties(FreeMarkerConfigurer factory) {
		factory.setTemplateLoaderPaths(this.properties.getTemplateLoaderPath());
		factory.setPreferFileSystemAccess(this.properties.isPreferFileSystemAccess());
		factory.setDefaultEncoding(this.properties.getCharsetName());
		Properties settings = new Properties();
		settings.putAll(this.properties.getSettings());
		factory.setFreemarkerSettings(settings);
	}

}
